package day_2022_4_to_7.leetcode;

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

/**
 * 2. 两数相加
 * @author haomin
 * @date 2022/05/17 17:37
 **/
public class Num2_addTwoNumbers {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(9);
        l1.next = new ListNode(9);
        l1.next.next = new ListNode(9);
        l1.next.next.next = new ListNode(9);

        ListNode l2 = new ListNode(9);
        l2.next = new ListNode(9);
        addTwoNumbers(l1,l2);
    }
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1 == null) return l2;
        if(l2 == null) return l1;

        int length1 = 0;
        int length2 = 0;
        for(ListNode x = l1;x != null;x = x.next) length1++;
        for(ListNode x = l2;x != null;x = x.next) length2++;

        ListNode longNode = length1 >= length2 ? l1 : l2;
        ListNode shortNode = length1 < length2 ? l1 : l2;
        ListNode newHead = longNode;
        int radix = 0;

        while (longNode != null && shortNode != null){
            longNode.val = longNode.val + shortNode.val + radix;
            radix = 0;
            if(longNode.val / 10 > 0){
                radix = longNode.val / 10;
                longNode.val = longNode.val % 10;
            }
            longNode = longNode.next;
            shortNode = shortNode.next;
        }

        while (longNode != null && radix != 0) {
            longNode.val = longNode.val + radix;
            radix = 0;
            if (longNode.val / 10 > 0) {
                radix = longNode.val / 10;
                longNode.val = longNode.val % 10;
            }
            longNode = longNode.next;
        }

        if (radix != 0) {
            ListNode tailNode = newHead;
            for (ListNode x = newHead; x.next != null; x = x.next) {
                tailNode = tailNode.next;
            }
            tailNode.next = new ListNode(radix);
        }
        return newHead;
    }
}